package cn.aitrox.ry.service.config.controller;

import cn.aitrox.ry.bean.CommonPageInfo;
import cn.aitrox.ry.bean.RespResult;
import cn.aitrox.ry.service.config.api.ComponentApi;
import cn.aitrox.ry.service.config.dto.ComponentDto;
import cn.aitrox.ry.service.config.dto.in.ComponentCreateInDto;
import cn.aitrox.ry.service.config.dto.in.ComponentEditInDto;
import cn.aitrox.ry.service.config.dto.in.ComponentSearchInDto;
import cn.aitrox.ry.service.config.entity.ComponentEntity;
import cn.aitrox.ry.service.config.service.ComponentService;
import cn.aitrox.ry.util.ArrayUtil;
import cn.aitrox.ry.util.BeanUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
public class ComponentController implements ComponentApi {

    @Autowired
    private ComponentService componentService;

    @PostMapping(value = "/config/component/search")
    @Override
    public CommonPageInfo<ComponentDto> search(@Validated @RequestBody ComponentSearchInDto input) {
        PageInfo<ComponentEntity> pageInfo = componentService.search(input.getPage(), input.getPageSize(), input.getIds(), input.getName());
        if (ArrayUtil.isEmpty(pageInfo.getList())) {
            return new CommonPageInfo(0, 0, null);
        }
        List<ComponentDto> list = pageInfo.getList().stream().map(x -> {
            ComponentDto component = new ComponentDto();
            BeanUtil.copy(x, component);
            return component;
        }).collect(Collectors.toList());
        return new CommonPageInfo(pageInfo.getTotal(), pageInfo.getPages(), list);
    }

    @PostMapping(value = "/config/component")
    @Override
    public RespResult create(@Validated @RequestBody ComponentCreateInDto input) {
        return componentService.create(input);
    }

    @PutMapping(value = "/config/component")
    @Override
    public RespResult edit(@Validated @RequestBody ComponentEditInDto input) {
        return componentService.edit(input);
    }

    @GetMapping(value = "/config/component/{id}")
    @Override
    public ComponentDto read(@PathVariable("id") Integer id) {
        ComponentEntity componentEntity = componentService.read(id);
        if (null == componentEntity) {
            return null;
        }
        ComponentDto component = new ComponentDto();
        BeanUtil.copy(componentEntity, component);
        return component;
    }
}
